import Router from "koa-router";
import { ApiResponse } from "../../types";
import axios from "axios";
import { config } from "../../config/env";
import { pool } from "../../config/database";
import { authMiddleware } from "../../middleware/auth";
import { RowDataPacket, ResultSetHeader } from "mysql2";
import { v4 as uuidv4 } from "uuid";
import { getChatManager } from "../../websocket/server";
import MarkdownIt from "markdown-it";

// 创建 markdown-it 实例
const md = new MarkdownIt({
  html: true,        // 允许 HTML 标签
  xhtmlOut: false,   // 使用 XHTML 输出
  breaks: true,      // 转换段落里的 '\n' 到 <br>
  linkify: true,     // 将类似URL的文本自动转换为链接
  typographer: true  // 启用一些语言中性的替换和引号美化
});

const router = new Router({ prefix: "/api/aiChat" });

// 处理CORS预检请求
router.options('/(.*)', async (ctx) => {
  ctx.status = 204;
});

// AI聊天接口 - POST请求 + WebSocket推送
router.post("/stream", authMiddleware, async (ctx) => {
  const { message, sessionId } = ctx.request.body as {
    message: string;
    sessionId?: string;
  };
  const userId = ctx.state.user.id as number;

  // 参数验证
  if (!message || message.trim().length === 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: "消息内容不能为空",
    } as ApiResponse;
    return;
  }

  // 生成或使用现有的会话ID
  const currentSessionId = sessionId || uuidv4();

  console.log(`🚀 收到AI聊天请求 - 用户: ${userId}, 消息: ${message}, 会话: ${currentSessionId}`);

  // 立即返回响应，不等待AI完成
  ctx.body = {
    success: true,
    data: {
      sessionId: currentSessionId,
      message: "AI聊天请求已接收，请通过WebSocket接收实时回复",
      timestamp: new Date().toISOString()
    },
    message: "请求已提交，正在处理中"
  } as ApiResponse;

  // 异步处理AI流式响应并通过WebSocket推送
  processAiChatAsync(userId, message, currentSessionId).catch(error => {
    console.error('异步AI聊天处理失败:', error);
  });
});

// 异步AI聊天处理函数
async function processAiChatAsync(userId: number, message: string, sessionId: string) {
  const chatManager = getChatManager();

  // WebSocket消息发送辅助函数
  const sendToUser = (type: string, data: any) => {
    console.log(`🔄 尝试发送WebSocket消息给用户 ${userId}, 类型: ${type}`);
    
    const success = chatManager.sendToUserId(userId, {
      type: type as any,
      data,
      sessionId,
      timestamp: Date.now()
    });
    
    if (success) {
      console.log(`✅ WebSocket消息发送成功: ${type}`);
    } else {
      console.log(`❌ WebSocket消息发送失败: ${type} - 用户 ${userId} 可能未连接`);
      
      // 获取详细的连接统计信息
      const stats = chatManager.getDetailedStats();
      console.log('📊 当前WebSocket连接状态:', JSON.stringify(stats, null, 2));
    }
    
    return success;
  };

  try {
    // 发送开始事件
    sendToUser('ai_chat_start', {
      sessionId: sessionId,
      userMessage: message.trim(),
      timestamp: new Date().toISOString()
    });

    // 1. 保存用户消息到数据库
    await pool.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [userId, sessionId, 'user', message.trim()]
    );
   
    // 2. 获取会话历史消息
    const [historyRecords] = await pool.execute(
      `SELECT message_type, content, created_at 
       FROM ai_chat_records 
       WHERE user_id = ? AND session_id = ? 
       ORDER BY created_at ASC 
       LIMIT 10`,
      [userId, sessionId]
    ) as [RowDataPacket[], any];

    // 3. 构建消息数组
    const messages = [
      {
        role: "system",
        content: "你是一个专业的装机指南助手，专门帮助用户选择电脑硬件、组装电脑和解决相关技术问题，用幽默风趣的语气回答。请提供准确、实用的建议。回答用Markdown风格。"
      }
    ];

    // 添加历史消息
    for (const record of historyRecords) {
      if (record.message_type === 'user') {
        messages.push({ role: "user", content: record.content });
      } else if (record.message_type === 'assistant') {
        messages.push({ role: "assistant", content: record.content });
      }
    }

    // 发送进度
    sendToUser('ai_chat_progress', { message: '正在连接AI服务...' });

    // 4. 发送流式请求到DeepSeek
    const response = await axios.post(
      `${config.deepseek.base_url}/chat/completions`,
      {
        model: config.deepseek.model,
        messages: messages,
        temperature: 0.7,
        max_tokens: 2000,
        stream: true
      },
      {
        headers: {
          'Authorization': `Bearer ${config.deepseek.apiKey}`,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream'
        },
        responseType: 'stream',
        timeout: 120000
      }
    );

    console.log('✅ AI流式连接成功');
    sendToUser('ai_chat_progress', { message: 'AI服务连接成功，开始生成回复...' });

    let fullResponse = '';
    let chunkCount = 0;

    // 处理DeepSeek流式数据
    let buffer = '';
    response.data.on('data', (chunk: Buffer) => {
      try {
        buffer += chunk.toString();
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';
        
        for (const line of lines) {
          const trimmedLine = line.trim();
          
          if (!trimmedLine || !trimmedLine.startsWith('data: ')) {
            continue;
          }

          const data = trimmedLine.slice(6).trim();
          
          if (data === '[DONE]') {
            console.log('🏁 AI流式响应完成');
            
            sendToUser('ai_chat_done', {
              fullResponse,
              htmlResponse: md.render(fullResponse),
              chunkCount,
              timestamp: new Date().toISOString()
            });
            return;
          }

          if (data) {
            try {
              const parsed = JSON.parse(data);
              const delta = parsed.choices?.[0]?.delta;
              
              if (delta?.content) {
                const content = delta.content;
                fullResponse += content;
                chunkCount++;
                
                // 将当前chunk渲染为HTML片段
                let htmlChunk = '';
                try {
                  // 渲染单个chunk为HTML（处理markdown语法）
                  htmlChunk = md.render(content);
                } catch (renderError) {
                  // 如果渲染失败，使用原文本
                  htmlChunk = content;
                  console.warn('❌ chunk HTML 渲染失败:', renderError);
                }
                
                // 发送包含HTML chunk的消息
                sendToUser('ai_chat_chunk', {
                  content,              // 原始文本chunk
                  htmlChunk,           // 渲染后的HTML chunk  
                  fullResponse,        // 完整原始文本（用于调试）
                  chunkIndex: chunkCount,
                  timestamp: new Date().toISOString()
                });
              }
            } catch (parseError) {
              console.warn('❌ 解析AI流式数据失败:', parseError);
            }
          }
        }
      } catch (error) {
        console.error('💥 处理AI流式数据块时出错:', error);
      }
    });

    // 处理流结束
    response.data.on('end', async () => {
      console.log('📝 AI流式响应结束，保存到数据库');

      if (fullResponse.trim()) {
        try {
          // 将 Markdown 转换为 HTML
          const htmlResponse = md.render(fullResponse.trim());

          // 保存原始 Markdown 到数据库
          await pool.execute(
            "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
            [userId, sessionId, 'assistant', fullResponse.trim()]
          );

          // 发送 HTML 版本给前端
          sendToUser('ai_chat_saved', {
            message: '对话已保存',
            htmlContent: htmlResponse,
            markdownContent: fullResponse.trim(),
            timestamp: new Date().toISOString()
          });
        } catch (saveError) {
          console.error('❌ 保存AI回复失败:', saveError);
          sendToUser('ai_chat_error', {
            message: '保存失败，但回复已生成',
            error: saveError
          });
        }
      }

      sendToUser('ai_chat_end', { message: 'AI对话完成' });
    });

    // 处理流错误
    response.data.on('error', (error: any) => {
      console.error('❌ AI流式数据错误:', error);
      sendToUser('ai_chat_error', {
        message: 'AI响应中断',
        error: error.message,
        timestamp: new Date().toISOString()
      });
    });

  } catch (error: any) {
    console.error('💥 AI聊天处理错误:', error);

    let userFriendlyMessage = "AI服务暂时不可用，请稍后重试";

    if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          userFriendlyMessage = "请求格式错误，请检查您的输入";
          break;
        case 401:
          userFriendlyMessage = "API密钥无效，请联系管理员";
          break;
        case 429:
          userFriendlyMessage = "请求过于频繁，请稍后重试";
          break;
        case 500:
        case 502:
        case 503:
        case 504:
          userFriendlyMessage = "AI服务暂时不可用，请稍后重试";
          break;
      }
    }

    sendToUser('ai_chat_error', {
      message: userFriendlyMessage,
      error: error.message,
      timestamp: new Date().toISOString()
    });

    // 保存错误信息到数据库
    try {
      await pool.execute(
        "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
        [userId, sessionId, 'assistant', `系统错误：${userFriendlyMessage}`]
      );
    } catch (dbError) {
      console.error("❌ 保存错误信息到数据库失败:", dbError);
    }

    sendToUser('ai_chat_end', { message: '请求处理完成' });
  }
}

// AI聊天接口 - 传统版本
router.post("/", authMiddleware, async (ctx) => {
  const { message, sessionId } = ctx.request.body as {
    message: string;
    sessionId?: string;
  };
  const userId = ctx.state.user.id as number;

  if (!message || message.trim().length === 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: "消息内容不能为空",
    } as ApiResponse;
    return;
  }

  const currentSessionId = sessionId || uuidv4();

  try {
    // 保存用户消息
    await pool.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [userId, currentSessionId, 'user', message.trim()]
    );

    // 获取历史消息
    const [historyRecords] = await pool.execute(
      `SELECT message_type, content, created_at 
       FROM ai_chat_records 
       WHERE user_id = ? AND session_id = ? 
       ORDER BY created_at ASC 
       LIMIT 10`,
      [userId, currentSessionId]
    ) as [RowDataPacket[], any];

    const messages = [
      {
        role: "system",
        content: "你是一个专业的装机指南助手，专门帮助用户选择电脑硬件、组装电脑和解决相关技术问题，且语气要幽默风趣。请提供准确、实用的建议，回答内容使用 Markdown 风格。"
      }
    ];

    for (const record of historyRecords) {
      if (record.message_type === 'user') {
        messages.push({ role: "user", content: record.content });
      } else if (record.message_type === 'assistant') {
        messages.push({ role: "assistant", content: record.content });
      }
    }

    // 发送请求到DeepSeek
    const response = await axios.post(
      `${config.deepseek.base_url}/chat/completions`,
      {
        model: config.deepseek.model,
        messages: messages,
        temperature: 0.7,
        max_tokens: 1000,
        stream: false
      },
      {
        headers: {
          'Authorization': `Bearer ${config.deepseek.apiKey}`,
          'Content-Type': 'application/json'
        },
        timeout: 30000
      }
    );

    const aiReply = response.data?.choices?.[0]?.message?.content || "抱歉，我无法理解您的问题，请重新描述。";

    // 将 Markdown 转换为 HTML
    const htmlReply = md.render(aiReply);

    // 保存原始 Markdown 到数据库
    await pool.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [userId, currentSessionId, 'assistant', aiReply]
    );

    ctx.body = {
      success: true,
      data: {
        sessionId: currentSessionId,
        userMessage: message.trim(),
        aiReply: aiReply,           // 原始 Markdown
        aiReplyHtml: htmlReply,     // 转换后的 HTML
        timestamp: new Date().toISOString(),
        usage: response.data?.usage || null
      },
      message: "AI对话成功",
    } as ApiResponse;

  } catch (error: any) {
    console.error("AI聊天错误:", error);

    let userFriendlyMessage = "AI服务暂时不可用，请稍后重试";

    if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          userFriendlyMessage = "请求格式错误，请检查您的输入";
          break;
        case 401:
          userFriendlyMessage = "API密钥无效，请联系管理员";
          break;
        case 429:
          userFriendlyMessage = "请求过于频繁，请稍后重试";
          break;
        case 500:
        case 502:
        case 503:
        case 504:
          userFriendlyMessage = "AI服务暂时不可用，请稍后重试";
          break;
      }
    }

    try {
      await pool.execute(
        "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
        [userId, currentSessionId, 'assistant', `系统错误：${userFriendlyMessage}`]
      );
    } catch (dbError) {
      console.error("保存错误信息到数据库失败:", dbError);
    }

    ctx.status = 500;
    ctx.body = {
      success: false,
      message: userFriendlyMessage,
      error: {
        type: "ai_error",
        message: error.message,
        timestamp: new Date().toISOString()
      },
      sessionId: currentSessionId,
      timestamp: new Date().toISOString()
    } as ApiResponse;
  }
});

// 获取聊天记录
router.get("/history", authMiddleware, async (ctx) => {
  const userId = ctx.state.user.id as number;
  const { sessionId, page = 1, limit = 20 } = ctx.query;

  try {
    const pageNum = parseInt(page as string);
    const limitNum = Math.min(parseInt(limit as string), 100);

    if (pageNum < 1 || limitNum < 1) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "页码和每页条数必须大于0",
      } as ApiResponse;
      return;
    }

    let sql = `
      SELECT id, session_id, message_type, content, created_at 
      FROM ai_chat_records 
      WHERE user_id = ?
    `;
    const params: any[] = [userId];

    if (sessionId) {
      sql += " AND session_id = ?";
      params.push(sessionId);
    }

    sql += " ORDER BY created_at ASC";

    const offset = (pageNum - 1) * limitNum;
    sql += ` LIMIT ${limitNum} OFFSET ${offset}`;

    const [records] = await pool.execute(sql, params) as [RowDataPacket[], any];

    // 获取总记录数
    let countSql = "SELECT COUNT(*) as total FROM ai_chat_records WHERE user_id = ?";
    const countParams: any[] = [userId];

    if (sessionId) {
      countSql += " AND session_id = ?";
      countParams.push(sessionId);
    }

    const [countResult] = await pool.execute(countSql, countParams) as [RowDataPacket[], any];
    const total = countResult[0].total;

    const formattedRecords = records.map(record => ({
      id: record.id,
      sessionId: record.session_id,
      messageType: record.message_type,
      content: record.content,                                  // 原始内容（Markdown）
      contentHtml: record.message_type === 'assistant' ?       // HTML 版本（仅对 AI 回复）
        md.render(record.content) :
        record.content,
      createdAt: record.created_at,
      isUser: record.message_type === 'user',
      isAssistant: record.message_type === 'assistant'
    }));

    ctx.body = {
      success: true,
      data: {
        records: formattedRecords,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          totalPages: Math.ceil(total / limitNum),
          hasNext: pageNum * limitNum < total,
          hasPrev: pageNum > 1
        }
      },
      message: "获取聊天记录成功",
    } as ApiResponse;

  } catch (error: any) {
    console.error("获取聊天记录错误:", error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "获取聊天记录失败",
      error: {
        type: "database_error",
        message: error.message,
        timestamp: new Date().toISOString()
      },
    } as ApiResponse;
  }
});

// 获取会话列表
router.get("/sessions", authMiddleware, async (ctx) => {
  const userId = ctx.state.user.id as number;
  const { page = 1, limit = 20 } = ctx.query;

  try {
    const pageNum = parseInt(page as string);
    const limitNum = Math.min(parseInt(limit as string), 100);

    if (pageNum < 1 || limitNum < 1) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "页码和每页条数必须大于0",
      } as ApiResponse;
      return;
    }

    const offset = (pageNum - 1) * limitNum;

    const [sessions] = await pool.execute(`
      SELECT 
        session_id,
        MIN(created_at) as first_message_time,
        MAX(created_at) as last_message_time,
        COUNT(*) as message_count,
        COUNT(CASE WHEN message_type = 'user' THEN 1 END) as user_message_count,
        COUNT(CASE WHEN message_type = 'assistant' THEN 1 END) as assistant_message_count,
        (SELECT content FROM ai_chat_records WHERE user_id = ? AND session_id = t.session_id AND message_type = 'user' ORDER BY created_at ASC LIMIT 1) as first_user_message,
        (SELECT content FROM ai_chat_records WHERE user_id = ? AND session_id = t.session_id ORDER BY created_at DESC LIMIT 1) as last_message
      FROM ai_chat_records t
      WHERE user_id = ?
      GROUP BY session_id
      ORDER BY last_message_time DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `, [userId, userId, userId]) as [RowDataPacket[], any];

    const [countResult] = await pool.execute(
      "SELECT COUNT(DISTINCT session_id) as total FROM ai_chat_records WHERE user_id = ?",
      [userId]
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;

    const formattedSessions = sessions.map(session => ({
      sessionId: session.session_id,
      firstMessageTime: session.first_message_time,
      lastMessageTime: session.last_message_time,
      messageCount: session.message_count,
      userMessageCount: session.user_message_count,
      assistantMessageCount: session.assistant_message_count,
      firstUserMessage: session.first_user_message,
      lastMessage: session.last_message,
      lastMessageHtml: session.last_message ?                   // HTML 版本的最后一条消息
        md.render(session.last_message) :
        null,
      title: session.first_user_message ?
        (session.first_user_message.length > 50 ?
          session.first_user_message.substring(0, 50) + '...' :
          session.first_user_message) :
        '新会话'
    }));

    ctx.body = {
      success: true,
      data: {
        sessions: formattedSessions,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          totalPages: Math.ceil(total / limitNum),
          hasNext: pageNum * limitNum < total,
          hasPrev: pageNum > 1
        }
      },
      message: "获取会话列表成功",
    } as ApiResponse;

  } catch (error: any) {
    console.error("获取会话列表错误:", error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "获取会话列表失败",
      error: {
        type: "database_error",
        message: error.message,
        timestamp: new Date().toISOString()
      },
    } as ApiResponse;
  }
});

// 删除会话
router.delete("/session/:sessionId", authMiddleware, async (ctx) => {
  const userId = ctx.state.user.id as number;
  const { sessionId } = ctx.params;

  if (!sessionId || sessionId.trim().length === 0) {
    ctx.status = 400;
    ctx.body = {
      success: false,
      message: "会话ID不能为空",
    } as ApiResponse;
    return;
  }

  try {
    // 检查会话是否存在
    const [existingRecords] = await pool.execute(
      "SELECT COUNT(*) as count FROM ai_chat_records WHERE user_id = ? AND session_id = ?",
      [userId, sessionId]
    ) as [RowDataPacket[], any];

    if (existingRecords[0].count === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: "会话不存在或您没有权限访问该会话",
      } as ApiResponse;
      return;
    }

    // 删除会话记录
    const [result] = await pool.execute(
      "DELETE FROM ai_chat_records WHERE user_id = ? AND session_id = ?",
      [userId, sessionId]
    ) as [ResultSetHeader, any];

    ctx.body = {
      success: true,
      data: {
        sessionId,
        deletedCount: result.affectedRows,
        deletedAt: new Date().toISOString()
      },
      message: "会话删除成功",
    } as ApiResponse;

  } catch (error: any) {
    console.error("删除会话错误:", error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "删除会话失败",
      error: {
        type: "database_error",
        message: error.message,
        sessionId: sessionId,
        timestamp: new Date().toISOString()
      },
    } as ApiResponse;
  }
});

export default router;
